package org.softee.messaging.redundancy;

import com.google.common.base.Charsets;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;

/**
 * Static factory that generates {@link KeyValueProvider} instances
 * @author extdivmoha
 *
 */
public class KeyValueProviders {
    private static final HashFunction hashFunction = Hashing.goodFastHash(128);

    public static class BasicKeyValueProvider<K, V> implements KeyValueProvider<K, V> {
        private final K key;
        private final V value;
        
        BasicKeyValueProvider(final K key, final V value) {
            this.key = key;
            this.value = value;
        }
        
        @Override
        public K getKey() {
            return key;
        }

        @Override
        public V getValue() {
            return value;
        }
        
        @Override
        public String toString() {
            return key + ": " + value;
        }
    }
    
    public static <K, V> KeyValueProvider<K, V> basic(final K key, final V value) {
        return new BasicKeyValueProvider<K, V>(key, value);
    }
    
    public static <K> KeyValueProvider<K, byte[]> messageDigest(final K key, final String value) {
        return messageDigest(key, value.getBytes(Charsets.UTF_8));
    }
    
    public static <K> KeyValueProvider<K, byte[]> messageDigest(final K key, final byte[] value) {
        final HashCode digest = hashFunction.hashBytes(value);
        return new BasicKeyValueProvider<K, byte[]>(key, digest.asBytes()) {
            @Override
            public String toString() {
                return key + ": " + digest.toString();
            }
        };
    }

}
